var env = process.env.NODE_ENV || 'development';
var Config = require('./common/config/configuration.json')[env];
var mysql = require("mysql");

var config = {};
for(var i in Config.database) {
    if(i !== "database") {
        config[i] = Config.database[i];
    }
}

var pool = mysql.createPool(config);

var init = function () {
    pool.getConnection(function (err, connection) {
        if (err) {
            console.log(err);
            return;
        }
        var init_data = require("./model/init.json").query;

        connection.query("SELECT * FROM "+Config.database.database+".user WHERE role='admin'", function (err,rows) {
            if(rows && rows[0] && rows[0].username === 'admin') {
                console.log("DB Check Finished. Data Exist");
                require("./bin/www");
            } else {
                initialize();
            }
        });

        var i = 0;
        function initialize() {
            connection.query(init_data[i], function (err,rows) {
                console.log(rows);
                err && console.error(err);
                if (++i < init_data.length) {
                    initialize();
                } else {
                    connection.release();
                    console.log("Data Init Finish");
                    require("./bin/www");
                }
            });
        }
    });
};
init();
